﻿using log4net;
using McsUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MinerManager.Forms
{
	public partial class MinerHashrate : Form
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;
		private int MinerId = 0;
		private string MinerName = string.Empty;
		private string FirstCurrencyName = string.Empty;
		private string SecondCurrencyName = string.Empty;
		private bool AllowTimerRefreshHashrate = true;//是否允许Timer执行刷新算力信息

		public event EventHandler<EventArgs> OnClose;

		public MinerHashrate(Common.AgentComponent agent, int minerId, string minerName, string firstCurrencyName, string secondCurrencyName)
		{
			InitializeComponent();
			this.Agent = agent;
			this.MinerId = minerId;
			this.MinerName = minerName;
			this.FirstCurrencyName = firstCurrencyName;
			this.SecondCurrencyName = secondCurrencyName;
		}

		#region 窗体事件

		private void MinerHashrate_Load(object sender, EventArgs e)
		{
			this.Agent.OnReceive += new EventHandler<RcvEventArgs>(Agent_OnReceive);

			Label_MinerName.Text = this.MinerName;

			//刷新数据
			RefreshHashrate();
			Action<object, EventArgs> refreshTick = delegate (object obj, EventArgs args)
			{
				RefreshHashrate();
			};

			Timer refreshHashrate = new Timer
			{
				Interval = 1000 * 2,
				Enabled = true
			};
			refreshHashrate.Tick += new EventHandler(refreshTick);
			refreshHashrate.Start();
		}

		private void MinerHashrate_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.Agent.OnReceive -= new EventHandler<RcvEventArgs>(Agent_OnReceive);
			this.OnClose?.Invoke(this, new EventArgs());
		}

		#endregion

		#region void Agent_OnReceive(object sender, RcvEventArgs e)

		private void Agent_OnReceive(object sender, RcvEventArgs e)
		{
			var proto = ProtocolHelper.GetProtoType(e.Buffer, body: out byte[] body);
			string json = System.Text.Encoding.UTF8.GetString(body);

			if (proto == ProtoType.NodeServerMinerManagerGetRedisData)
			{
				List<McsUtility.Models.RedisDataModel> result = ProtocolHelper.ReadPackageBody<List<McsUtility.Models.RedisDataModel>>(body);
				ShowHashrate(result);
			}
		}

		#endregion



		#region void RefreshHashrate() 刷新矿机数据。

		private delegate void DelegateRefreshHashrate();

		/// <summary>
		/// 刷新矿机数据。
		/// </summary>
		private void RefreshHashrate()
		{
			//设置是否允许刷新算力信息，不允许刷新时终止执行
			if (this.AllowTimerRefreshHashrate)
				this.AllowTimerRefreshHashrate = false;
			else
				return;

			if (this.InvokeRequired)
			{
				DelegateRefreshHashrate d = new DelegateRefreshHashrate(RefreshHashrate);
				this.BeginInvoke(d);
			}
			else
			{
				//发送数据
				if (this.Agent.IsStarted)
				{
					byte[] bytes = ProtocolHelper.WritePackage<int[]>(ProtoType.MinerManagerGetRedisData, new int[] { this.MinerId });
					this.Agent.AgentSend(bytes);
				}
			}
		}

		#endregion

		#region void ShowHashrate(List<McsUtility.Models.RedisDataModel> infos) 显示矿机信息。

		private delegate void DelegateShowHashrate(List<McsUtility.Models.RedisDataModel> infos);

		/// <summary>
		/// 显示矿机信息。
		/// </summary>
		private void ShowHashrate(List<McsUtility.Models.RedisDataModel> infos)
		{
			if (this.InvokeRequired)
			{
				DelegateShowHashrate d = new DelegateShowHashrate(ShowHashrate);
				this.BeginInvoke(d, infos);
			}
			else
			{
				if (infos.Count > 0 && !string.IsNullOrWhiteSpace(infos[0].RedisData))
				{
					Models.MinerHashrate infoRedis = TomNet.Utility.Data.JsonHelper.FromJson<Models.MinerHashrate>(infos[0].RedisData);

					List<string> ta = infoRedis.Ta.ConvertListString(';');
					List<string> tb = infoRedis.Tb.ConvertListString(';');
					List<string> sa = infoRedis.Sa.ConvertListString(';');
					List<string> sb = infoRedis.Sb.ConvertListString(';');
					List<string> tmpFan = infoRedis.TmpFan.ConvertListString(';');

					Label_First_CurrencyName.Text = this.FirstCurrencyName;
					Label_First_Hashrate.Text = (ta[0].ConvertDecimal() / 1000).ToString("0.000") + "MH/S";
					Label_First_Success.Text = ta[1];
					Label_First_Failure.Text = ta[2];

					Label_Second_CurrencyName.Text = this.SecondCurrencyName;
					Label_Second_Hashrate.Text = (tb[0].ConvertDecimal() / 1000).ToString("0.000") + "MH/S";
					Label_Second_Success.Text = tb[1];
					Label_Second_Failure.Text = tb[2];

					TableList.Items.Clear();
					int num = sa.Count > sb.Count ? sa.Count : sb.Count;
					for (int i = 0; i < num; i++)
					{
						string sai = sa.Count > i ? sa[i] : "0";
						string sbi = sb.Count > i ? sb[i] : "off";
						
						string firstHashrate = !sai.Equals("Off", StringComparison.CurrentCultureIgnoreCase) ? (sai.ConvertDecimal() / 1000).ToString("0.00") + "MH/S" : sai;
						string secondHashrate = !sbi.Equals("Off", StringComparison.CurrentCultureIgnoreCase) ? (sbi.ConvertDecimal() / 1000).ToString("0.00") + "MH/S" : sbi;
						string tmp = tmpFan.Count > i * 2 ? tmpFan[i * 2] + "℃" : "-";
						string fan = tmpFan.Count > i * 2 + 1 ? tmpFan[i * 2 + 1] + "%" : "-";

						ListViewItem item = new ListViewItem(new string[] { (i + 1).ToString(), firstHashrate, secondHashrate, tmp, fan });
						TableList.Items.Add(item);
					}
				}

				//设置是否允许刷新算力信息为允许
				this.AllowTimerRefreshHashrate = true;
			}
		}

		#endregion
	}
}
